/*
 * @Descripttion:
 * @version:
 * @Author: ChenXiang
 * @Date: 2021-04-07 10:55:38
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-06-23 14:25:36
 */
import React from "react";
import http from "@/common/request"; // 此处是用mockjs模拟的数据
// useMutation处理数据的增/删/改
// useQuery处理数据的查
// react-query的更多api 可以查看 https://blog.csdn.net/weixin_43294560/article/details/115049649
import { useQuery, useMutation, useQueryClient } from "react-query";

export default (props) => {
  const queryClient = useQueryClient();
  // list是此查询的键
  const {
    data = [],
    status,
    refetch,
  } = useQuery("list", async () => {
    return await http.Demo.tables();
  });

  // 删除用户
  const del = useMutation((params) => http.Demo.tableDel(params), {
    // 让缓存失效
    onSuccess: () => {
      // 使得匹配的查询失效并重新获取
      queryClient.invalidateQueries("list");
    },
  });

  // 查询用户
  const search = useMutation((params) => http.Demo.tableInfo(params), {
    // 让缓存失效
    onSuccess: (data, variables, context) => {
      // 查询成功后替换掉list
      queryClient.setQueryData("list", [data]);
    },
  });
  return (
    <div>
      <button
        onClick={() => {
          refetch();
        }}
      >
        再次渲染
      </button>

      <button
        onClick={() => {
          search.mutate({ id: 3 });
        }}
      >
        查询用户
      </button>

      <button
        onClick={() => {
          del.mutate({ id: 5 });
        }}
      >
        删除用户
      </button>

      {status === "error" && <p>请求失败</p>}
      {status === "loading" && <p>请求中</p>}
      {status === "success" && <div>请求成功</div>}

      <ul>
        {data.map((item) => (
          <li key={item.id}>
            11{item?.c} typeof{" "}
            {console.log(Object.prototype.toString.call(item?.c))}
          </li>
        ))}
      </ul>
      <ul>
        {data.map((item) => (
          <li key={item.id}>11{item?.name}</li>
        ))}
      </ul>
    </div>
  );
};
